package benny.ApkposStore.utils;

import java.io.File;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.sqlite.SQLiteDatabase;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CacheManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import benny.ApkposStore.R;
import benny.ApkposStore.Activity.RoomtableActivity;
import benny.ApkposStore.db.DBHelper;

public class ApkUntils {
	static String[] itemText = { "1", "2", "3", "4", "5", "6", "7", "8", "9",
			"0", "del", "OK" };
	static int[] animarray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
	private static SimpleDateFormat dateformat;


	// 获取最新流水号
		public static String getOdno_var_new(Activity ddd,String dateorder) {
		    int orderint=0;
			
			String dateold = ApkUntils.ReadSharedPreferences(ddd, "odnotable", "date");
			
			if (!dateorder.equals(dateold)) {
				ApkUntils.WriteSharedPreferences(ddd, "odnotable", "date", dateorder);				
				orderint = 1;
				ApkUntils.WriteSharedPreferences(ddd, "odnotable", "id", orderint+"");
			} else {
				String idstr = ApkUntils.ReadSharedPreferences(ddd, "odnotable", "id");
				if ((!idstr.equals(""))&(idstr!=null)) {
					orderint=Integer.parseInt(idstr);	
				}
				else {
					orderint=0;
				}
				orderint = orderint + 1;
				ApkUntils.WriteSharedPreferences(ddd, "odnotable", "id", orderint+"");
			}

			String orderstr = orderint + "";
			while (orderstr.length() < 4) {
				orderstr = "0" + orderstr;
			}

			String orderid = dateorder + orderstr + Apkglobal.getposid();
			System.out.println(orderid + "   " + orderint);
			System.out.println("Apkglobal.getposid():"
					+ Apkglobal.getposid());
			
			return orderid;
			
			}
	
	// 取得自定义数字键盘的Adapter
	public static ListAdapter getMenuAdapter(Activity ddd) {
		ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
		Field[] fields = R.drawable.class.getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			if (fields[i].getName().startsWith("keyb")) { // // 所有keyb*命名的图片
				HashMap<String, Object> map = new HashMap<String, Object>();
				try {
					map.put("img", fields[i].getInt(R.drawable.class));
					map.put("itemText", itemText[i]);
				} catch (Exception e) {

				}
				data.add(map);
			}
		}

		SimpleAdapter simperAdapter = new SimpleAdapter(ddd, data,
				R.layout.softkeyboard_item_menu, new String[] { "img",
						"itemText" }, new int[] { R.id.item_image_softkeyboard,
						R.id.item_text_softkeyboard });
		return simperAdapter;

	}
	

	//Unicode转UTF8
	public static  String decodeUnicode(String theString) {
		char aChar;
		int len = theString.length();
		StringBuffer outBuffer = new StringBuffer(len);
		for (int x = 0; x < len;) {
			aChar = theString.charAt(x++);
			if (aChar == '\\') {
				aChar = theString.charAt(x++);
				if (aChar == 'u') {
					// Read the xxxx
					int value = 0;
					for (int i = 0; i < 4; i++) {
						aChar = theString.charAt(x++);
						switch (aChar) {
						case '0':
						case '1':
						case '2':
						case '3':
						case '4':
						case '5':
						case '6':
						case '7':
						case '8':
						case '9':
							value = (value << 4) + aChar - '0';
							break;
						case 'a':
						case 'b':
						case 'c':
						case 'd':
						case 'e':
						case 'f':
							value = (value << 4) + 10 + aChar - 'a';
							break;
						case 'A':
						case 'B':
						case 'C':
						case 'D':
						case 'E':
						case 'F':
							value = (value << 4) + 10 + aChar - 'A';
							break;
						default:
							throw new IllegalArgumentException(
									"Malformed   \\uxxxx   encoding.");
						}

					}
					outBuffer.append((char) value);
				} else {
					if (aChar == 't')
						aChar = '\t';
					else if (aChar == 'r')
						aChar = '\r';
					else if (aChar == 'n')
						aChar = '\n';
					else if (aChar == 'f')
						aChar = '\f';
					outBuffer.append(aChar);
				}
			} else
				outBuffer.append(aChar);
		}
		return outBuffer.toString();
	}
	
	//退出系统
	public static void quit(Activity aa) {
		   File file = CacheManager.getCacheFileBaseDir();
		   if (file != null && file.exists() && file.isDirectory()) {
		    for (File item : file.listFiles()) {
		     item.delete();
		    }
		    file.delete();
		   }

		   aa.deleteDatabase("webview.db");
		   aa.deleteDatabase("webviewCache.db");

		// 目前最为通用的 关闭进程的方法以后的版本使用
		Intent startMain = new Intent(Intent.ACTION_MAIN);
		startMain.addCategory(Intent.CATEGORY_HOME);
		startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		aa.startActivity(startMain);
		android.os.Process.killProcess(android.os.Process.myPid());

	}
	
	//读取hashmap文件
		public static String gethashmap(List<HashMap<String, Object>> list,String key) {
			String str = null;
			for (Iterator<HashMap<String, Object>> iterator = list.iterator(); iterator.hasNext();) {
				HashMap<String, Object> hashMap = (HashMap<String, Object>) iterator
						.next();
				str=hashMap.get(key).toString();	
				
			}
			return str;
		}

	//读取配置文件
	public static String ReadSharedPreferences(Activity aa, String filename,
			String strName) {
		String str = null;
		SharedPreferences file = aa.getSharedPreferences(filename, 0);
		str = file.getString(strName, "");
		return str;
	}
	
	//保存配置文件
	public static void WriteSharedPreferences(Activity aa, String filename,
			String strName, String strvalue) {
		SharedPreferences file = aa.getSharedPreferences(filename, 0);
		Editor editor = file.edit();
		editor.putString(strName, strvalue);
		editor.commit();

	}

	// 获取UUID+设备号序列号 唯一识别码（不可变）
	public static String getMyUUID(Activity aa) {

		final TelephonyManager tm = (TelephonyManager) aa.getBaseContext()
				.getSystemService(Context.TELEPHONY_SERVICE);

		final String tmDevice, tmSerial,  androidId;

		tmDevice = "" + tm.getDeviceId();

		tmSerial = "" + tm.getSimSerialNumber();

		androidId = ""
				+ android.provider.Settings.Secure.getString(
						aa.getContentResolver(),
						android.provider.Settings.Secure.ANDROID_ID);

		UUID deviceUuid = new UUID(androidId.hashCode(),
				((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());

		String uniqueId = deviceUuid.toString();

		return uniqueId;

	}

	// java 获取可变UUID

	public String getMyUUIDww() {

		UUID uuid = UUID.randomUUID();

		String uniqueId = uuid.toString();

		return uniqueId;

	}

	// /escape编码
	public static String escape(String src) {
		int i;
		char j;
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(src.length() * 6);
		for (i = 0; i < src.length(); i++) {
			j = src.charAt(i);
			if (Character.isDigit(j) || Character.isLowerCase(j)
					|| Character.isUpperCase(j))
				tmp.append(j);
			else if (j < 256) {
				tmp.append("%");
				if (j < 16)
					tmp.append("0");
				tmp.append(Integer.toString(j, 16));
			} else {
				tmp.append("%u");
				tmp.append(Integer.toString(j, 16));
			}
		}
		return tmp.toString();
	}

	// /escape解码
	public static String unescape(String src) {
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(src.length());
		int lastPos = 0, pos = 0;
		char ch;
		while (lastPos < src.length()) {
			pos = src.indexOf("%", lastPos);
			if (pos == lastPos) {
				if (src.charAt(pos + 1) == 'u') {
					ch = (char) Integer.parseInt(
							src.substring(pos + 2, pos + 6), 16);
					tmp.append(ch);
					lastPos = pos + 6;
				} else {
					ch = (char) Integer.parseInt(
							src.substring(pos + 1, pos + 3), 16);
					tmp.append(ch);
					lastPos = pos + 3;
				}
			} else {
				if (pos == -1) {
					tmp.append(src.substring(lastPos));
					lastPos = src.length();
				} else {
					tmp.append(src.substring(lastPos, pos));
					lastPos = pos;
				}
			}
		}
		return tmp.toString();
	}

	public static float getPixelsintW(Activity aa) {
		DisplayMetrics dm = new DisplayMetrics();
		aa.getWindowManager().getDefaultDisplay().getMetrics(dm);
		int width = dm.widthPixels;
		float a = (float) (width / 800.0000);
		return a;
	}

	public static float getPixelsintH(Activity aa) {

		DisplayMetrics dm = new DisplayMetrics();
		aa.getWindowManager().getDefaultDisplay().getMetrics(dm);
		int height = dm.heightPixels;
		float a = (float) (height / 600.00);
		return a;
	}

	// 全屏
	public static void fullscreen(Activity aa) {
		Apkglobal.setcurrentapiVersion(android.os.Build.VERSION.SDK_INT);
		aa.requestWindowFeature(Window.FEATURE_NO_TITLE);
		if (Apkglobal.getcurrentapiVersion() > 10) {
			//aa.getWindow().getDecorView().setSystemUiVisibility(4);
		} else {
			aa.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FULLSCREEN);
		}
	}

	// 转换dip为px
	public static int convertDIP2PX(Context context, int dip) {
		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));
	}

	// 转换px为dip
	public static int convertPX2DIP(Context context, float f) {
		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (f / scale + 0.5f * (f >= 0 ? 1 : -1));
	}

	public static String downloadxml(String urlstr) {
		HttpDownloader httpdownloader = new HttpDownloader();
		String result = httpdownloader.download(urlstr);
		return result;
	}

	// 动态改变VIEW的布局
	public static void changeviewlayout(AbsListView view, int width,
			int height, BaseAdapter adapter) {
		LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) view
				.getLayoutParams(); // 取控件当前的布局参数
		if (width > 0) {
			linearParams.width = width;
		}
		if (height > 0) {
			linearParams.height = height;
		}
		view.setLayoutParams(linearParams); // 使设置好的布局参数应用到控件

		if (Apkglobal.getcurrentapiVersion() <= 10) {
			//view.setAdapter(adapter);
		}

	}

	// 动态改变VIEW的布局
	// public static void changelistviewlayout(ListView view, int width,
	// int height,BaseAdapter adapter) {
	// LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) view
	// .getLayoutParams(); // 取控件当前的布局参数
	// if (width > 0) {
	// linearParams.width = width;
	// }
	// if (height > 0) {
	// linearParams.height = height;
	// }
	// view.setLayoutParams(linearParams); // 使设置好的布局参数应用到控件
	//
	// if (Apkglobal.getcurrentapiVersion()<=10) {
	// view.setAdapter(adapter);
	// }
	//
	// }

	// 动态改变VIEW的布局
	public static void changeviewlayoutMargin(GridView view, int top, int left,
			int right, int bottom) {
		RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) view
				.getLayoutParams(); // 取控件当前的布局参数
		if (top > 0) {
			linearParams.topMargin = top;

		}
		if (left > 0) {
			linearParams.leftMargin = left;
		}
		if (right > 0) {
			linearParams.rightMargin = right;
		}
		if (bottom > 0) {
			linearParams.bottomMargin = bottom;
		}
		view.setLayoutParams(linearParams); // 使设置好的布局参数应用到控件

	}

	// 动态显示View
	public static void ViewVisible(View view) {
		Animation animation = new AlphaAnimation(0, 1.0f);
		animation.setDuration(500);
		view.setAnimation(animation);
		view.setVisibility(View.VISIBLE);
	}

	// 动态隐藏View
	public static void ViewInvisible(View view) {
		Animation animation = new AlphaAnimation(1.0f, 0);
		animation.setDuration(500);
		view.setAnimation(animation);
		view.setVisibility(View.INVISIBLE);
	}

	public static void openActivityAnim(Activity aaa, int num) {
		if (num < 0) {
			Random dd = new Random();
			num = dd.nextInt(animarray.length);// 随机找动画
            System.out.println("随机找动画:"+num);
		}

		switch (num) {
		case 0:
			/*
			 * 注意：此方法只能在startActivity和finish方法之后调用。
			 * 第一个参数为第一个Activity离开时的动画，第二参数为所进入的Activity的动画效果
			 */
			aaa.overridePendingTransition(R.anim.fade, R.anim.hold);
			break;
		case 1:
			aaa.overridePendingTransition(R.anim.my_scale_action,
					R.anim.my_alpha_action);
			break;
		case 2:
			aaa.overridePendingTransition(R.anim.scale_rotate,
					R.anim.my_alpha_action);
			break;
		case 3:
			aaa.overridePendingTransition(R.anim.scale_translate_rotate,
					R.anim.my_alpha_action);
			break;
		case 4:
			aaa.overridePendingTransition(R.anim.scale_translate_in,
					R.anim.my_alpha_action);
			break;
		case 5:
			aaa.overridePendingTransition(R.anim.hyperspace_in,
					R.anim.hyperspace_out);
			break;
		case 6:
			aaa.overridePendingTransition(R.anim.push_left_in,
					R.anim.push_left_out);
			break;
		case 7:
			aaa.overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
			break;
		case 8:
			aaa.overridePendingTransition(R.anim.slide_left, R.anim.slide_right);
			break;
		case 9:
			aaa.overridePendingTransition(R.anim.wave_scale,
					R.anim.my_alpha_action);
			break;
		case 10:
			aaa.overridePendingTransition(R.anim.zoom_enter,
					R.anim.scale_translate_out);
			break;
		case 11:
			aaa.overridePendingTransition(R.anim.slide_up_in,
					R.anim.slide_down_out);
			break;
		}
	}


	// 读取一段数组数据作为测试数据,并返回一个SimpleAdapter
	public static SimpleAdapter ReadtestArray(Activity ddd, int array,
			int layout, int id) {
		SimpleAdapter simpleAdapter = null;
		// String[] dishtypeArry = ddd.getResources().getStringArray(array);
		String[] dishtypeArry = { "", "", "", "", "", "", "", "", "", "", "",
				"", "", "", "", "", "", "", "", "", "", "", "", "", "" };
		List<HashMap<String, String>> dishtypes = new ArrayList<HashMap<String, String>>();
		for (int i = 0; i < array; i++) {
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("name", dishtypeArry[i]);
			dishtypes.add(map);
		}
		simpleAdapter = new SimpleAdapter(ddd, dishtypes, layout,
				new String[] { "name" }, new int[] { id });
		return simpleAdapter;
	}

	// 读取一段数组数据作为测试数据,并返回一个List
	public static List<Map<String, Object>> ReadtestList(Activity ddd, int array) {
		String[] dishtypeArry = ddd.getResources().getStringArray(array);
		List<Map<String, Object>> dishtypes = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < dishtypeArry.length; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("name", dishtypeArry[i]);
			dishtypes.add(map);
		}
		return dishtypes;
	}

	// 转换小数
	public static String convertFloat(String value, int num) {// value是你的值，num是你截取小数点的位数
		String result = "";
		try {
			if (value.equals("")) {
				value = "0";
			}
			result = String.valueOf((float) Math.round(Float.parseFloat(value)
					* Math.pow(10, num))
					/ Math.pow(10, num));
		} catch (Exception e) {
			System.out.print(e.getMessage());
		}
		return result;
	}
	
	//关闭系统键盘
	public static void closeSystemKeyBoard(Context mcx,EditText et){
		  InputMethodManager imm = (InputMethodManager) mcx.getSystemService(Context.INPUT_METHOD_SERVICE);
		        imm.hideSoftInputFromWindow(et.getWindowToken(), 1);
		 }
	
	// 打开数字键盘
	public static void opensoftkeyboard(final EditText editText,
			final GridView gridView, ListAdapter MenuAdapter, final int modu) {
		if (!Apkglobal.getkey_false()) {
			Apkglobal.setkey_false(true);
		}
		gridView.setSelector(R.color.transparent);
		gridView.setAdapter(MenuAdapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {

			StringBuffer sBuffer = new StringBuffer(editText.getText()
					.toString().trim());

			StringBuffer sBuffer1 = new StringBuffer();
			int index = 0;

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
              
				if (modu == 1) {
					switch (arg2) {
					case 10:
						if (sBuffer1.length() > 0) {
							sBuffer1.deleteCharAt(sBuffer1.length() - 1);
						}
						break;
					case 11:

						if (gridView.getVisibility() == View.VISIBLE) {
							// ApkUntils.ViewVisible(gridView);
							sBuffer1 = new StringBuffer(editText.getText()
									.toString().trim());
							Animation animation1 = AnimationUtils
									.loadAnimation(gridView.getContext()
											.getApplicationContext(),
											R.anim.scale_translate_out);
							gridView.setAnimation(animation1);
							gridView.setVisibility(View.INVISIBLE);
							editText.setFocusable(false);

						}

						break;

					default:
						if (gridView.getVisibility() == View.VISIBLE) {
						if (arg2 == 9) {
							sBuffer1.append(0);
						} else {							
								sBuffer1.append(arg2 + 1);	
								System.out.println("ddddddddddddddd");
							}
							
							
						}
					}

					editText.setText(sBuffer1);
					editText.setSelection(sBuffer1.length());
				} else {
					index = editText.getSelectionStart();
					switch (arg2) {
					case 10:
						if (index > 0) {
							sBuffer.delete(index - 1, index);
							index--;
						}
						break;
					case 11:

						if (gridView.getVisibility() == View.VISIBLE) {
							// ApkUntils.ViewVisible(gridView);
							Animation animation1 = AnimationUtils
									.loadAnimation(gridView.getContext()
											.getApplicationContext(),
											R.anim.scale_translate_out);
							gridView.setAnimation(animation1);
							gridView.setVisibility(View.INVISIBLE);
							editText.setFocusable(false);

						}

						break;

					default:
						if (arg2 == 9) {
							sBuffer.insert(index, 0);
						} else {
							sBuffer.insert(index, arg2 + 1);
						}
						index++;
					}

					editText.setText(sBuffer.toString());
					editText.setSelection(index);
				}

			}
		});
	}
	
	///显示键盘
	public static void keyboardtouchup(final EditText editText, GridView gridView,
			ListAdapter MenuAdapter,Context cx) {
		if (gridView.getVisibility() == View.INVISIBLE) {
			// ApkUntils.ViewVisible(gridView);

			Animation animation1 = AnimationUtils.loadAnimation(
					cx, R.anim.scale_translate_in);
			gridView.setAnimation(animation1);
			gridView.setVisibility(View.VISIBLE);
			editText.setFocusable(true);
			editText.setFocusableInTouchMode(true);
			editText.requestFocus();
			editText.selectAll();
	
		} else {

			Animation animation2 = AnimationUtils.loadAnimation(
					cx, R.anim.scale_translate_out);
			gridView.setAnimation(animation2);
			editText.clearFocus();
			editText.setFocusable(false);
			gridView.setFocusable(true);
			gridView.setFocusableInTouchMode(true);
			gridView.requestFocus();
			gridView.setVisibility(View.INVISIBLE);


			// ApkUntils.ViewInvisible(gridView);

		}

	}
	
	public static void execSQL (Context cx,String sql) {
		synchronized(ApkConstant.SQLLOCK) {	
			try {
				
				SQLiteDatabase db =null; 
				db = DBHelper.getWritableDatabase(cx);	
				db.execSQL(sql);
				db.close();
				db=null;
				
			} catch (Exception e) {
				Log.e(sql, e.getMessage());
				e.printStackTrace();
			}
		
	}
	}

}
